﻿using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using My.Core.Options;
using My.Framework;
using My.Framework.AspNetCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My.Core.Startup
{
	public class CorsAccessorStartup : StartupModule<CorsAccessorStartup>
	{
		/// <summary>
		/// 程序启动器
		/// </summary>
		public CorsAccessorStartup() => Order = 1;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="webApplicationBuilder"></param>
		public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
		{
			Console.WriteLine("CorsAccessorStartup");
			var services = webApplicationBuilder.Services;

			// 读 跨域 配置
			string[] corsUrls = App.GetConfig<string[]>("corsUrls");
			
			//配置跨域
			services.AddCors(c =>
			{
				c.AddPolicy("Policy", policy =>
				{
					policy.WithOrigins(corsUrls ?? Array.Empty<string>())
					.AllowAnyHeader()//允许任意头
					.AllowCredentials()//允许cookie
					.AllowAnyMethod();//允许任意方法
									  // AllowAnyOrigin表示允许任何域；
				});
			});
			//services.AddIPRate(builder.Configuration);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="webApplication"></param>
		public override void Configure(WebApplication webApplication)
		{
			// 配置CORS中间件，Policy为策略名称
			// UseCors 必须在 UseRouting 之后，UseResponseCaching、UseAuthorization 之前
			webApplication.UseCors("Policy");
		}
	}
}
